<template>
    <div id="app">
        <div class="con">
            <el-dl v-for="(item,index) in list" :key="index" 
                :url="item.imgUrl"
                :title="item.title"
                :con="item.con"
                :price="item.price"
                :num="item.num"
                :id="item.id"
            ></el-dl>
        </div>
        <div>数量：{{totalNum}} 价格：{{totalPrice}}</div>
    </div>
</template>

<script>
import elDl from './components/el-dl'
export default {
    data(){
        return {
            list:[],
            buyList:[]
        }
    },
    components:{
        elDl
    },
    created(){
        this.getData();
        this.$bus.$on('add',(id,num) => {
            let index = this.list.findIndex(item => item.id === id);
            let isBuy = this.buyList.findIndex(bItem => bItem.id === id);
            this.list[index].num = num;
            if(isBuy == -1){
                this.buyList.push(this.list[index]);
            }
        })
    },
    computed:{
        totalNum(){
            return this.buyList.reduce((pre,cur) => {
                return pre + cur.num
            },0)
        },
        totalPrice(){
            return this.buyList.reduce((pre,cur) => {
                return pre + cur.price*cur.num
            },0)
        }
    },
    methods:{
        getData(){
            this.$http('/api/product').then((res) => {
                if(res.data.code === 1){
                    let data = res.data.data.map(item => {
                        item.num = 0;
                        return item
                    })
                    this.list = data;
                }
                console.log(res);
            }).catch((error) => {
                console.warn(error)
            })
        }
    }
}
</script>

<style>
@import "./assets/common.css";

</style>
